var Dataset = require('../models').Dataset
var User = require('../models').User
var eventproxy = require('eventproxy');
exports.search = function(req,res,next){
  var q = req.query.q;
  var proxy = new eventproxy();
  proxy.fail(next);
  var result = {user: req.session.user || null};

  //使用proxy来完成异步
  // Dataset.find({$or:[
  //   {"title":{"$regex":q,"$options":"i"}},
  //   {"description":{"$regex":q,"$options":"i"}}
  // ]}, function(err, datasets){
  //   if (err){console.log("err: ",err)}
  //   console.log(datasets)
  //   res.render('search',{
  //     'user':req.session.user | null,
  //     'datasets': datasets
  //   })
  // })

  Dataset.find({$or:[
    {"title":{"$regex":q, "$options":"i"}},
    {"description":{"$regex":q, "$options":"i"}}
  ]}, proxy.done('datasets', function(datasets){
    return datasets;
  }));

  User.find({$or: [
    {"name":{"$regex":q, "$options":"i"}},
    {"email":{"$regex":q, "$options":"i"}}
  ]}, proxy.done('users', function(users){
    return users;
  }));

  proxy.all('users','datasets', function(users, datasets){
    console.log(datasets, users)
    res.render('search', {
      'user': req.session.user || null,
      'datasets': datasets,
      'users': users
    })
  })
}
